import {
  FILL_HOT_WORDS,
  FILL_SEARCH_RESULT,
  FILL_SEARCH_HISTORY,
  FILL_SEARCH_SUGGEST,
  FILL_MATCH_LIST,
  CLEAR_SEARCH_RESULT
} from "./types";
import {
  hotWords,
  suggestWords,
  search as reqSearch,
  getMatchList
} from "../../../api/summary";
import { createSong } from "../../../assets/js/songModel";
const fillHotWrods = data => ({ type: FILL_HOT_WORDS, data });
export const fillSearchResult = data => ({ type: FILL_SEARCH_RESULT, data });
const fillSearchHistory = data => ({ type: FILL_SEARCH_HISTORY, data });
const fillSearchSuggest = data => ({ type: FILL_SEARCH_SUGGEST, data });
export const fillMatchList = data => ({ type: FILL_MATCH_LIST, data }); // 最佳匹配列表
export const clearSearchResult = () => ({ type: CLEAR_SEARCH_RESULT });

export const getHotWrodsAction = () => async dispatch => {
  try {
    const res = await hotWords();
    if (res.code === 200) {
      dispatch(fillHotWrods(res.result.hots));
    }
  } catch (error) {}
};

export const getSuggestAction = keyword => async dispatch => {
  try {
    const res = await suggestWords(keyword);
    if (res.code === 200) {
      dispatch(fillSearchSuggest(res.result.allMatch || []));
    }
  } catch (error) {}
};

export const getSearchResult = (
  keyword,
  offset = 0,
  limit = 20
) => async dispatch => {
  try {
    const res = await reqSearch(keyword, offset, limit);
    const res2 = await getMatchList(keyword);
    const res3 = await Promise.all([res, res2]);
    if (res3[0].code === 200 && res3[1].code === 200) {
      let result = {};
      res3.forEach((item, i) => {
        if (i === 0) {
          let songs = item.result.songs
            ? item.result.songs.map(song => createSong(song))
            : [];
          songs.songCount = item.result.songCount;
          result["songs"] = songs;
        }
        if (i === 1) {
          let matchs = [];
          if (item.result.orders) {
            for (let key in item.result) {
              let oItem = item.result[key][0];
              if (key === "video" || key === "orders" || key === "rec_query") {
                continue;
              }
              oItem.type = key;
              matchs.push(oItem);
            }
            result["matchs"] = matchs;
          } else {
            result["matchs"] = [];
          }
        }
      });
      dispatch(fillSearchResult(result));
    }
  } catch (error) {
    console.log(error);
  }
};

// export const getMutipleMatchList = keyword => async dispatch => {
//   try {
//     const res = await getMatchList(keyword);
//     if (res.code === 200) {
//       if (res.result.orders) {
//         let arr = [];
//         for (let key in res.result) {
//           let item = res.result[key][0];
//           if (key == "video" || key == "orders") {
//             continue;
//           }
//           item.type = key;
//           arr.push(item);
//         }
//         dispatch(fillMatchList(arr));
//       }
//     }
//   } catch (error) {}
// };
